/*
*  removePCB
*  This function checks 2 queues for a given PCB and removes it if possible
*  Justin Hamric
*  returns a 1 if the pcb was found and deleted
*  returns a 0 if it was not found
*/

#include <string.h>
#include <stdlib.h>
#include "mpx_pcb.h"
#include "mpx_supt.h"

//when called, you would say removePCB(&pcbJ, &pcbqJ)
int removePCB(struct MPX_PCB* pcbJ, struct MPX_Q* pcbqR, struct MPX_Q* pcbqB){//pcbqR - ready queue, pcbqB - blocked queue
	/*
	Traverse the queue, compare the name of the PCB to the name at the current position
	If the name is what we're looking for, set PCB.next.prev = PCB.prev
										   set PCB.prev.next = PCB.next
										   set PCB.next = NULL  
										   set PCB.prev = NULL
	If the name isn't found before count is reached, send a message	saying
	the pcb couldn't be found
	*/
	struct MPX_PCB* current = (*pcbqR).head;
	int found = 0; //changed name form deleted to found (a bit less cryptic)
	/*
	 * NEED TO ADD ERROR CHECKING FOR IF ONLY PCB IN THE QUEUE
	 * AND IF PCB IS HEAD OR TAIL...MAYBE...
	 */
	while(current != NULL){
		if(!strcmp((*current).processName, (*pcbJ).processName)){//found the process
			found = 1;
			(*pcbqR).count--; //make sure we keep track of number of processes in the queue
		}else{
		current = (*current).next;
		}
	}
	current = (*pcbqB).head;
	while(current != NULL){
		if(!strcmp((*current).processName, (*pcbJ).processName)){//found the process
			found = 1;
			(*pcbqB).count--; //make sure we keep track of number of processes in the queue
		}else{
		current = (*current).next;
		}
	}
	if(found == 0){
		printf("No PCB with that name was found.\n");
		return 0;
	}else if((*pcbJ).next == NULL){ //if its the tail
		(*(*pcbJ).prev).next = NULL;
		if((*(*pcbJ).prev).pcb_state == 1){
			(*pcbqR).tail = (*pcbJ).prev;
		}
		if((*(*pcbJ).prev).pcb_state == -1){
			(*pcbqB).tail = (*pcbJ).prev;
		}
		(*pcbJ).next = NULL;
		(*pcbJ).prev = NULL;
		return 1;
	}else if((*pcbJ).prev == NULL){ //if its the head
		(*(*pcbJ).prev).prev = NULL;
		if((*(*pcbJ).prev).pcb_state == 1){
			(*pcbqR).head = (*pcbJ).next;
		}
		if((*(*pcbJ).prev).pcb_state == -1){
			(*pcbqB).head = (*pcbJ).next;
		}
		(*pcbJ).next = NULL;
		(*pcbJ).prev = NULL;
		return 1;
	}else{
		(*(*pcbJ).next).prev = (*pcbJ).prev; //double pointers trolololo
		(*(*pcbJ).prev).next = (*pcbJ).next;
		(*pcbJ).next = NULL;
		(*pcbJ).prev = NULL;
		printf("The given PCB was found and removed.\n");
		return 1;
	}
}
